package cn.lishiyuan.algorithm.strings;

/**
 * 暴力匹配算法
 */
public class BFMatcher implements Matcher{

    @Override
    public boolean match(CharSequence source, CharSequence word) {
        return find(source,word) != -1;
    }

    @Override
    public int find(CharSequence source, CharSequence word) {
        // codePoints或者chars
        int[] sourceArray = source.chars().toArray();
        int[] wordsArray = word.chars().toArray();

        if (sourceArray.length < wordsArray.length){
            return -1;
        }

        if (wordsArray.length == 0){
            return -1;
        }

        int index = -1;

        for (int i = 0; i < (sourceArray.length - wordsArray.length + 1); i++) {
            // 逐字匹配
            boolean match = true;
            for (int j = 0; j < wordsArray.length; j++) {
                if(sourceArray[i+j] != wordsArray[j]){
                    match = false;
                    break;
                }
            }
            // 已匹配
            if(match){
                index = i;
                break;
            }
        }

        return index;
    }
}
